package com.crazy.practice.boot.core;

import com.alibaba.fastjson.JSON;
import com.crazy.entity.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author panyonghui
 * @describe 全局响应
 * @date 2022/1/20 19:41
 */
@Slf4j
@Order(9)
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @Value("${response.success.message}")
    private String defaultMessage;

    @Value("${response.success.message.key}")
    private String defaultMessageKey;

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        // 判断是否要执行beforeBodyWrite方法，true为执行，false不执行
        return true;
    }

    /**
     * @describe 对响应数据进行包装处理
     * @auther crazy_cat
     * @date 2022/1/20 20:44
     * @param o
     * @param methodParameter
     * @param mediaType
     * @param aClass
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @return java.lang.Object
     * @modify
     */
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        Object object;
        if (o instanceof CommonResponse){
            object = o;
        } else {
            CommonResponse commonResponse = new CommonResponse();
            commonResponse.setResCode(defaultMessageKey);
            commonResponse.setResMsg(defaultMessage);
            commonResponse.setData(o);
            object = commonResponse;
        }
        if (o instanceof String){
            object = JSON.toJSONString(object);
        }
        log.info("响应数据:{}", JSON.toJSONString(object));
        return object;
    }
}
